<template>
  <div class="users">
    <breadcrumb></breadcrumb>
    <el-card>
      <!-- 搜索框的制作 -->
      <el-row :gutter="20">
        <el-col :span="8"> 
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="8"> 
          <el-button type="primary" @click="adddialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户表单的制作 -->
      <el-table  :data="userlist" :border="true" :stripe="true">
         <el-table-column type="index" ></el-table-column>
         <el-table-column  label="姓名" prop="username"></el-table-column>
         <el-table-column  label="邮箱" prop="email"></el-table-column>
         <el-table-column  label="电话" prop="mobile"></el-table-column> 
         <el-table-column  label="角色" prop="role_name"></el-table-column> 
         <el-table-column  label="状态" >
           <template slot-scope="scope">
             <el-switch v-model="scope.row.mg_state" @change="statechange(scope.row)">
             </el-switch>
           </template>
         </el-table-column>
         <el-table-column  label="操作" width="180px">
           <template slot-scope="scope">
             <el-tooltip class="item" effect="dark" content="编辑信息" placement="top-start" :enterable="false">
             <el-button type="primary" icon="el-icon-edit" size="mini" @click="edituser(scope.row.id)"></el-button>
             </el-tooltip>
             <el-tooltip class="item" effect="dark" content="删除信息" placement="top-start" :enterable="false">
             <el-button type="danger"  icon="el-icon-delete" size="mini" @click="deleteuser(scope.row.id)"></el-button>
             </el-tooltip>
             <el-tooltip class="item" effect="dark" content="分配权限" placement="top-start" :enterable="false">
                <el-button type="warning" icon="el-icon-setting" size="mini" @click="settingrole(scope.row)"></el-button>
             </el-tooltip>
           </template>
         </el-table-column>
      </el-table>
      <!-- 分页栏制作 -->
       <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size ="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalusers">
    </el-pagination>
     <!-- 添加用户对话框 -->
      <el-dialog title="添加用户" :visible.sync="adddialogVisible" width="50%" >
       <el-form  :model="adduser" :rules="adduserrules" ref="adduserref" label-width="80px">
        <el-form-item label="用户名:" prop="username">
          <el-input v-model="adduser.username"></el-input>
        </el-form-item>
        <el-form-item label="密码:" prop="password">
          <el-input v-model="adduser.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" prop="email">
          <el-input v-model="adduser.email"></el-input>
        </el-form-item>
        <el-form-item label="电话:" prop="mobile">
          <el-input v-model="adduser.mobile"></el-input>
        </el-form-item>
       </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="clearmsg">取 消</el-button>
        <el-button type="primary" @click="verify">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户对话框 -->
      <el-dialog title="修改用户" :visible.sync="editdialogVisible" width="50%" >
       <el-form  :model="editform" :rules="editformrules" ref="editformref" label-width="80px">
        <el-form-item label="用户名:" prop="username">
          <el-input v-model="editform.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" prop="email">
          <el-input v-model="editform.email"></el-input>
        </el-form-item>
        <el-form-item label="电话:" prop="mobile">
          <el-input v-model="editform.mobile"></el-input>
        </el-form-item>
       </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="editclear">取 消</el-button>
        <el-button type="primary" @click="editverify" >确 定</el-button>
        </span>
      </el-dialog>
       <!-- 设置分配角色的表单 -->
        <el-dialog title="设置分配角色" :visible.sync="roledialogVisible" width="50%" @close="roleclose" >
          <div>
            <p>当前的用户：{{userinfo.username}}</p>
            <p>当前的角色：{{userinfo.role_name}}</p>
            <p>分配新角色：
              <el-select v-model="selectroleid" placeholder="请选择">
                <el-option
                  v-for="item in rolelist"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id">
                </el-option>
              </el-select></p>

          </div>
          <span slot="footer" class="dialog-footer">
          <el-button @click="cancelrole">取 消</el-button>
          <el-button type="primary" @click="confirmrole">确 定</el-button>
          </span>
        </el-dialog>
    </el-card>
  </div>
</template>

<script>

import breadcrumb from "../../component/content/breadcrumb.vue"
import {netrequest} from "../../network/request.js"
import {checkemail,checkmobile} from "../../component/common/utils.js"

export default {
  name: 'users',
  data(){
    return{
      // 获取用户的列表数据对象
      queryInfo:{
        query:'',
        pagenum: 1 ,
        pagesize: 2 
      },
      userlist:[],
      totalusers:null,
      adddialogVisible:false,
      adduser:{
        username:null,
        password:null,
        email:null,
        mobile:null
      },
      adduserrules:{
          username:[ 
                { required: true, message: '请输入用户名称', trigger: 'blur' },
                { min: 3, max: 7, message: '长度在 3 到 7 个字符', trigger: 'blur' }
            ],
          password:[ 
                { required: true, message: '请输入密码', trigger: 'blur' },
                { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
            ],
            email:[
                {  required: true, message: '请输入邮箱地址', trigger: 'blur' },
                { validator:checkemail , trigger: 'blur'}
            ],
            mobile:[
                { required: true, message: '请输入手机号', trigger: 'blur' },
                { validator:checkmobile , trigger: 'blur'}
            ]
      },
      editdialogVisible:false,
      editform:{},
      editformrules:{
        email:[
                {  required: true, message: '请输入邮箱地址', trigger: 'blur' },
                { validator:checkemail , trigger: 'blur'}
            ],
        mobile:[
                { required: true, message: '请输入手机号', trigger: 'blur' },
                { validator:checkmobile , trigger: 'blur'}
            ]
      },
      roledialogVisible:false,
      userinfo:{},
      selectroleid:'',
      rolelist:null
    }
  },
  components:{
    breadcrumb
  },
  methods:{
     async getUserList(){
      const {data : res} = await netrequest({method:'get',url:'/users',params:this.queryInfo})
        console.log(res);
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg)
        this.userlist = res.data.users
        this.totalusers = res.data.total
        console.log(this.userlist);
     },
     async handleCurrentChange(newpage){
       this.queryInfo.pagenum = newpage
       const {data:res} = await netrequest({method:'get',url:'/users',params:this.queryInfo})
       if(res.meta.status !==200) return this.$message.error(res.meta.msg)
       this.$message.success(res.meta.msg)
       this.userlist = res.data.users
     },
     async handleSizeChange(newsize){
       this.queryInfo.pagesize = newsize
       const {data:res} = await netrequest({method:'get',url:'/users',params:this.queryInfo})
       if(res.meta.status !==200) return this.$message.error(res.meta.msg)
       this.$message.success(res.meta.msg)
       this.userlist = res.data.users
     },
     async statechange(usermsg){
      console.log(usermsg);
      const {data:res} = await netrequest({method:'put',url:`users/${usermsg.id}/state/${usermsg.mg_state}`})
      console.log(res);
      if(res.meta.status !== 200) {
         this.$message.error(res.meta.msg)
         usermsg.mg_state = !usermsg.mg_state
      }
      
      this.$message.success(res.meta.msg)
     },
     clearmsg(){
       this.adddialogVisible = false;
       this.$refs.adduserref.resetFields()
     },
     verify(){
       this.$refs.adduserref.validate(async(val)=>{
         if(!val) return 

         const {data:res} = await netrequest({method:'post',url:'/users',data:this.adduser})
         console.log(res);
          if(res.meta.status !== 201) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          this.adddialogVisible = false;
          this.$refs.adduserref.resetFields()
          this.getUserList()
       })
     },
     async edituser(id){
       this.editdialogVisible = true
       console.log(id);
       const {data : res} = await netrequest({method:'get',url:'/users/'+id})
       if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
       this.$message.success(res.meta.msg)
       this.editform = res.data
     },
     editclear(){
       this.editdialogVisible = false
       this.$refs.editformref.resetFields()
     },
     editverify(){
        this.$refs.editformref.validate(async valid=>{
          if(!valid) return
          this.editdialogVisible = false
          const {data:res} = await netrequest({method:'put',url:'/users/'+this.editform.id,data:{
            email:this.editform.email,
            mobile:this.editform.mobile
          }})
          if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          this.getUserList()
          
        }) 
     },
     async deleteuser(id){
      
       const confirmresult = await this.$confirm.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
         confirmButtonText: '确定',
         cancelButtonText: '取消',
         type: 'warning'
        }).catch((error) => {
          error
          });

        if(confirmresult !== 'confirm') return
        const {data:res} = await netrequest({method:'delete',url:'/users/'+id})
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getUserList()
     },
    //  分配角色的点击事件
     async settingrole(userinfo){
       this.userinfo = userinfo
       const {data:res} = await netrequest({method:'get',url:'/roles'})
       if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
       this.rolelist = res.data
       this.roledialogVisible = true
     },
    //  分配用户角色
    async confirmrole(){
       if(!this.selectroleid) return this.$message('请选择角色')
      const {data:res} = await netrequest({method:'put',url:`users/${this.userinfo.id}/role`,data:{rid:this.selectroleid}})
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.roledialogVisible = false
        this.getUserList()
     },
     roleclose(){
       this.selectroleid = ''
     },
    cancelrole(){
     this.roledialogVisible = false
   }
     },
  created(){
    this.getUserList()
  }
}
</script>

<style>



</style>

